package com.kayt.cyberBar.cuser.business.dao.impl;

import java.math.BigInteger;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.kayt.cyberBar.common.PageData;
import com.kayt.cyberBar.common.dao.EntityDao;
import com.kayt.cyberBar.common.property.PublicCodeConfigInfo;
import com.kayt.cyberBar.cuser.business.dao.IWorkRequestDao;
import com.kayt.cyberBar.cuser.business.entity.po.BWorkRequest;

@Repository("workRequestDao")
public class WorkRequestDaoImpl implements IWorkRequestDao {
	@Autowired
	private EntityDao entityDao;
	@Autowired
	private PublicCodeConfigInfo configInfo;

	@Override
	public Long saveWorkRequest(BWorkRequest workRequest) throws SQLException {
		return entityDao.save(workRequest);
	}

	@Override
	public PageData<BWorkRequest> findWorkRequestByStoreCode(String storeCode, Integer pageNum, Integer pageSize)
			throws SQLException {
		PageData<BWorkRequest> pageData = new PageData<>();
		String sql = "SELECT wq.* FROM b_work_request wq,b_user u,b_organization_depart_user b1,"
				+ "b_organization_store_depart b2 WHERE u.USER_CODE = b1.USER_CODE AND u.USER_CODE "
				+ "= wq.USER_CODE AND b1.STORE_DEPART_CODE = b2.STORE_DEPART_CODE AND b2.STORE_CODE = '" + storeCode
				+ "' and u.STATUS_CODE != '"+configInfo.getUserStatusDelete()+"' order by REQ_TIME desc";
		String countSql = "SELECT count(*) as count FROM b_work_request wq,b_user u,b_organization_depart_user b1,"
				+ "b_organization_store_depart b2 WHERE u.USER_CODE = b1.USER_CODE AND u.USER_CODE "
				+ "= wq.USER_CODE AND b1.STORE_DEPART_CODE = b2.STORE_DEPART_CODE AND b2.STORE_CODE = '" + storeCode
				+ "' and u.STATUS_CODE != '"+configInfo.getUserStatusDelete()+"'";
		List<BWorkRequest> pageList = entityDao.getPagingDataBySql(BWorkRequest.class, pageNum, pageSize, sql, null);
		List<Map<String, Object>>  countResult = entityDao.getPagingDataBySql(countSql, -1, -1, null);
		BigInteger count = (BigInteger) countResult.get(0).get("count");
		pageData.setTotal(count.longValue());
		pageData.setPageList(pageList);
		return pageData;
	}

	@Override
	public BWorkRequest findWorkRequestByReuqestCode(String requestCode) throws SQLException {
		String sql = "select * from b_work_request where REQUEST_CODE ='"+requestCode+"'";
		List<BWorkRequest> requestList = entityDao.getPagingDataBySql(BWorkRequest.class, -1, -1, sql, null);
		if(requestList != null && requestList.size() != 0){
			return requestList.get(0);
		}else{
			return null;
		}
	}

	@Override
	public void updateWorkRequest(BWorkRequest entity) {
		if(entity != null){
			entityDao.update(entity);
		}
	}

}
